import React,{Component} from 'react'
import Pages from '../Pages'
import '../../style/css/layer.css'
import $ from 'jquery'
import Dropzone from 'react-dropzone'
import Layer from '../Layer'
import {Spin,message,Tooltip} from 'antd';
import * as pub from '../../config/public';
import * as fetch from '../../config/fetch';
class AddBook extends Component {
	constructor(props) {
		super(props)
		
		this.state = {
			visible: false,
			modalShows:false,
			cover_image:[],
			is_choose_image:false,
			bookEntityName:this.props.book.bookEntityName?this.props.book.bookEntityName:'',
			bookEntityPath:this.props.book.bookEntityPath?this.props.book.bookEntityPath:'',
			book:this.props.book?this.props.book:{},
			tsChecked:false,
			zlChecked:false,
			typeList:this.props.typeList,
			texts:this.props.texts,
			status:'',
			bookId:this.props.bookId?this.props.bookId:'',
			bookPath:this.props.book.bookPath?this.props.book.bookPath:'',
			error_bookName:false,
			error_author:false,
			error_cashIntegral:false,
			loadBtning:false,
			fileTypes:true
		}
		
	}

	componentWillReceiveProps(nextProps) {
			this.setState({
				book:nextProps.book,
				typeList:nextProps.typeList,
				texts:nextProps.texts,
				modalShows:nextProps.modalShows,
				bookId:nextProps.bookId,
				status:nextProps.status,
				visible:nextProps.modalShow,
				bookPath:nextProps.book.bookPath,
				bookEntityPath:nextProps.book.bookEntityPath,
				bookEntityName:nextProps.book.bookEntityName
			},()=>{
				console.log(this.state)
				if(this.state.bookPath === undefined){
					return;
				}
				let optionValue=this.state.book.operationType==='1'?0:1;
				$('.book-class').find("input[type='radio']").eq(optionValue).attr("checked",true);
				if(optionValue===0){
                   this.setState({
			           fileTypes:true
		           })
				}else{
                   this.setState({
				     fileTypes:false
			       })
				}
			})

    }
	showModal = () => {
		this.setState({
			visible: true,
			texts:"新增图书",
			status:'',
			book:{},
			cover_image:[],
			bookEntityPath:"",
			bookEntityName:"",
			modalShows:false,
			bookPath:''
		},()=>{
			let radio = $('input[name=operationType]');
			radio[0].checked = true;
		});
	}
	hideMdoal = (e) => {
		$('.layer').addClass('layer-anim-close');
		setTimeout(() => {
			$('.layer').removeClass('layer-anim-close');
			this.setState({
				visible: false,
				book:{},
				status:'',
				cover_image:"",
				bookPath:"",
				modalShow:false,
				loadBtning:false,
				bookEntityPath:''
			});
		}, 10)
	}
	chooseImage(accepted, rejected){
		this.setState({
			cover_image:accepted[0],
			is_choose_image:true,
			bookPath: ''
		})
	}

	add(e) {
		e.preventDefault();
		if(this.refs.bookName.value === ''){
			this.setState({error_bookName:true});
			return;
		}else{
			if(this.refs.bookName.value.length>15){
				message.warning('图书名称不能超过15字！');
				return;
			}
			this.setState({error_bookName:false});
		}
		if(this.refs.Author.value === ''){
			this.setState({error_author:true});
			return;
		}else{
            if(this.refs.Author.value.length>10){
				message.warning('作者名不能超过10字！');
				return;
			}
			this.setState({error_author:false});
		}
		if(this.refs.cashIntegral.value === ''){
			this.setState({error_cashIntegral:true});
			return
		}else{
			if(this.refs.cashIntegral.value.length>8){
				message.warning('兑换积分不能超过8位！');
				return;
			}
			this.setState({error_cashIntegral:false});
		}
		if(this.refs.Press.value.length>10){
			    message.warning('出版社不能超过10字！');
				return;
		}
		if(this.refs.Subhead.value.length>15){
			    message.warning('副标题不能超过15字！');
				return;
		}
		if(this.refs.originalAuthor.value.length>10){
			message.warning('原作名不能超过10字！');
			return;
		}
		if(this.refs.Translator.value.length>10){
            message.warning('译者不能超过10字！');
			return;
		}
		if(this.refs.publishYear.value.length>20){
			message.warning('出版年不能超过20字！');
			return;
		}
		if(this.refs.bookName.value === ''){
			this.refs.bookName_tip.style.display = 'block';
		}
		if(this.refs.Pages.value.length>5){
            message.warning('页数不能超过5位！');
			return;
		}
		if(this.refs.cashIntegral.value.length>8){
			message.warning('兑换积分不能超过8位！');
			return;
		}
		if (!this.state.is_choose_image) {
			if(this.state.bookPath===''){
                message.error('请选择封面图片', 3);
			    return;
			}
		}
		var formData = new FormData();
		formData.append('bookState','A');
		formData.append('operationType', $('input[type="radio"][name="operationType"]:checked').val());
		if(this.state.status==="编辑"){
				//let fileImg,fileFile,fileList=[];
				
				if(this.state.bookPath!==''){
				formData.append('file',this.state.bookPath);
				//fileImg=this.state.bookPath;
				}else{
					//fileImg=this.state.cover_image;	
					formData.append('file',this.state.cover_image);
				}
				if(this.state.bookEntityPath!==''){
					//fileFile=this.state.bookEntityPath;
				formData.append('fileBook',this.state.bookEntityPath);
				}else{
					//fileFile=$('#book_file')[0].files[0];
				formData.append('fileBook',$('#book_file')[0].files[0]);
			}
			formData.append('bookId',this.state.bookId);
				// fileList.push(fileImg);
				// fileList.push(fileFile);
				// formData.append('file',fileList);
		}else{
             formData.append('file',this.state.cover_image);
			 formData.append('file',$('#book_file')[0].files[0]);
		}
		for (let x in this.refs) {
			formData.append(x,this.refs[x].value);
		}
		// if(this.state.bookId!==''){
		// 	formData.append('bookId',this.state.bookId);
		// }
        if(this.state.status==="编辑"){
		
			this.fetchEdit(formData);
			
		}else{
			this.fetchAdd(formData);
			
		}
	}  
	numberInput = (e) => {
		let value = e.target.value;
		if( value.length>5){
			message.error("只能为5位数");
		}else{
			e.target.value = value.replace(/[^\d]/g,'');
		}
	} 
	numberInputs=(e)=>{
		let value = e.target.value;
		e.target.value = value.replace(/[@#%￥&{}?/><[()（）【】{}《》''“‘”’....]+/g,'');
	}
	fetchAdd(formData){
		pub.loadBtning(this,true);
		fetch.bookManage(formData).then((data) => {
			if(data.result === 'RC100'){
				this.setState({
		       	        visible: false,
						book:{},
						modalShow:false,
						cover_image:[],
						bookPath:''
		        });
				this.props.show();
			}else{
				message.error(data.errMsg,3);
			}
			pub.loadBtning(this,false);
		}, (res) => {
			pub.reject(res);
			this.setState({
				loading: false
			})
			pub.loadBtning(this,false);
		})
	}
	fetchEdit(formData){
		pub.loadBtning(this,true);
		fetch.bookUpdate(formData).then((data) => {
			if(data.result === 'RC100'){
				
				this.setState({
			          visible: false,
					  status:'',
					  book:{},
					  modalShow:false,
					  cover_image:[],
					  bookPath:''
		        });
	 			this.props.show();
			}else{
				message.error(data.errMsg,3);
			}
			pub.loadBtning(this,false);
		}, (res) => {
			pub.reject(res);
			this.setState({
				loading: false
			})
			pub.loadBtning(this,false);
		})
	} 


	checkType(){
			$('#book_file').val('')
			this.setState({
				fileTypes:false
			})
			this.refs.cashIntegral.disabled = true;
			this.refs.cashIntegral.value = 0;
	}
	checkType1(){
		$('#book_file').val('')
		message.success('选择文件只能为pdf格式',3);
		this.setState({
			fileTypes:true
		})
		this.refs.cashIntegral.disabled = false;
		this.refs.cashIntegral.value ="";
	}
	chooseBook(accept){
		console.log(accept)
		let file = $('#book_file')[0].files[0];
	    let fileName = $('#book_file')[0].files[0].name;
	    let start = fileName.lastIndexOf('.');
	    let type = fileName.slice(start+1,fileName.length);
		for(let i in accept){
			if(type.indexOf(accept[i])!==-1){
				return;
			}
		}
		$('#book_file').val('');
	}

	render() {
		let book = this.state.book;
		return (
			<div>

			<Layer
					title={this.state.texts}
					show={this.state.visible}
					hide={(e) => this.hideMdoal(e)}
					width="800px"
					height="500px"
				>
				<Spin spinning={this.state.loadBtning} tip="发布中...">
					<form className="layui-layer-content"
						onSubmit={(e) => this.add(e)}
					>
						<div className="row">
							<div className="pop-box-1">
								<div className="book-add clearFix">
									<div className="book-class">
										<p>
											<label className='label-book'><input type="radio" onClick={() => this.checkType1()} required="required" name='operationType' value="1"  disabled={this.state.modalShows} />图书</label>
											<label className='label-book2'><input  onClick={() => this.checkType()} type="radio" required="required" name='operationType' value="2" disabled={this.state.modalShows} />资料</label>
										</p>
										{
											this.state.bookPath !==''?
											<img src={pub.getFile(this.state.bookPath)} alt='封面图片' />
											:
											<img src={this.state.cover_image.preview} alt='封面图片' />
										}
									</div>
									<ul className="book-info">
										{/*<li><label><span>*</span>图书渠道：</label><select><option>1</option></select></li>*/}
										<li><label><span>*</span>图书分类：</label>
											<select ref='bookType' required="required" defaultValue={book.bookType}>
												{this.state.typeList.map((type, index) => {
													return (
														<option key={index} value={type.code}>{type.name}</option>
													)
												})}
											</select></li>
										 <li><label><span>*</span>书籍名称：</label><Tooltip visible={this.state.error_bookName} title="请输入书籍名称"><input type="text" defaultValue={book.bookName} ref='bookName' onKeyUp={this.numberInputs} /></Tooltip></li> 
										<li><label><span>*</span>作者：</label><Tooltip visible={this.state.error_author} title="请输入作者"><input type="text" defaultValue={book.author} ref='Author' onKeyUp={this.numberInputs} /></Tooltip></li>
										<li><label>出版社：</label><input type="text" defaultValue={book.press} ref='Press' onKeyUp={this.numberInputs} /></li>
										<li><label>副标题：</label><input type="text" defaultValue={book.subhead} ref='Subhead' onKeyUp={this.numberInputs}/></li>
										<li><label>原作名：</label><input type="text" defaultValue={book.originalAuthor} ref='originalAuthor' onKeyUp={this.numberInputs} /></li>
										<li><label>译者：</label><input type="text" defaultValue={book.translator} ref='Translator' onKeyUp={this.numberInputs} /></li>
										<li><label>出版年：</label><input type="text" defaultValue={book.publishYear} ref='publishYear' onKeyUp={this.numberInputs} /></li>
										<li><label>页数：</label><input type="text" defaultValue={book.pages} ref='Pages' id="Num" onKeyUp={this.numberInput} /></li>
										<li><label><span>*</span>兑换积分：</label><Tooltip visible={this.state.error_cashIntegral} title="请输入兑换积分"><input type="text"  defaultValue={book.cashIntegral} ref='cashIntegral' onKeyUp={this.numberInput} /></Tooltip></li>
										<li>
											<label style={{ marginLeft: '92px' }}><span>*</span>图书文件:</label>
											{
												this.state.bookEntityPath!==''?
												<div>
													<a href={pub.getFile(this.state.bookEntityPath)} style={{display:'block',marginLeft:'414px',textAlign:'left',paddingBottom:'5px'}}>{this.state.bookEntityName}</a>
													<a className='book_file choose-again' style={{marginLeft:'214px'}} onClick={()=>{this.setState({bookEntityPath:''})}}>重新选择文件</a>
												</div>:
												<div>
												{
													this.state.fileTypes?<input onChange={(e)=>this.chooseBook(['pdf'])} className='book_file' id='book_file' required="required" type="file"  accept=".pdf"/>
													:<input onChange={(e)=>this.chooseBook(['xls','doc','txt','pdf'])} className='book_file' id='book_file' required="required"  type="file" accept=".xls,.doc,.txt,.pdf"/>
												}
											
													
													<span style={{ fontSize: "10px", marginLeft: "630px", position: "relative", top: "-25px", color: "red" }}>(不能选择图片)</span>
												</div>
											}
										</li>
									</ul>

									<Dropzone
										// maxSize= {31457280}
										multiple={false}
										onDrop={this.chooseImage.bind(this)}
										className='choose-image'
										accept="image/jpeg, image/png"
									>
										<label htmlFor="file" className="file">上传封面</label>

									</Dropzone>

								</div>
							</div>
							<div className="pop-btn">
								<a className="btn btn-grey layui-layer-close" onClick={(e) => this.hideMdoal(e)}>取消</a>
								<button type='submit' className="btn add-book" >确定</button>
							</div>
						</div>
					</form>
				  </Spin>
				</Layer>

				<a className="btn btn-blue" onClick={() => this.showModal()}>新增</a>
			</div>
		)
	}
}

class BookManage extends Component {
	constructor(args) {
		super()
		this.state = {
			BookList: pub.getObject(0),
			activeIndex: 0,
			tooltip: null,
			totalPage: 1,
			loading: false,
			typeList: [],
			texts:"",
			bookType: '',
			operationType: '',
			bookState: '',
			jumpPage: 1,
			bookName: '',
			book: {},
			status: '',
			bookId: '',
			modalShow: false,
			modalShows:true
		}

	}

	componentWillMount() {
		pub.loading(this,true);
		fetch.prepareinsertBook({
			pid: 1
		}).then((data) => {
			if (data.result === 'RC100') {
				this.setState({
					typeList: data.categoriesList
				}, () => {
					this.show();
				})
			} else {
				message.error(data.errMsg, 3);
				pub.loading(this, false);
			}
		}, (res) => {
			pub.reject(res);
			this.setState({
				loading: false
			});
		})

	}
	show() {
		let body = {};
		body.bookState = this.state.bookState;
		body.bookType = this.state.bookType;
		body.operationType = this.state.operationType;
		body.pageno = this.state.jumpPage;
		body.bookName = this.state.bookName;
		this.setState({
			loading: true
		});
		fetch.bookManageList(body).then((data) => {
			if (data.result === 'RC100') {
							this.setState({
				BookList: data.bookList,
				totalPage: data.totalPage,

			}, () => {
				this.setState({
					loading: false
				});
			})
			}else{
				message.error(data.errMsg, 3);
				pub.loading(this, false);
			}


		}, (res) => {
			pub.reject(res);
			this.setState({
				loading: false
			});
		})
		this.setState({
			modalShow: false
		})
	}
	jump(page) {
		this.setState({
			jumpPage: page
		}, () => {
			this.show();
		})
	}
	delBook(bookId,value){
		this.setState({
			modalShow:false
		},()=>{
            let formData = new FormData();
			if(value===1){
                 formData.append('bookState','A');
			}else{
                 formData.append('bookState','D');
			}
			formData.append('bookId',bookId);
			fetch.bookManage(formData).then((data) => {
				if (data.result === 'RC100') {
					this.show();
					
				} else {
					message.error(data.errMsg, 3);
				}
			})
		})
	}
	removeBooks(bookId){
		let formData = new FormData();
		formData.append('bookId',bookId);
			fetch.removeBook(formData).then((data) => {
				if (data.result === 'RC100') {
					this.show();
				} else {
					message.error(data.errMsg, 3);
				}
			})
	}
	editBook(bookId) {
		fetch.selectBook({ bookId }).then((data) => {
			if (data.result === 'RC100') {
				//this.clickTrue();
				this.setState({
					bookId,
					book: data.book,
					status: '编辑',
					modalShow: true,
					modalShows: true,
					texts:"编辑图书"
					
				})
			} else {
				message.error(data.errMsg, 3);
			}
		})
	}
	// clickTrue(){
	// 	this.refs.cashIntegra.disabled=true
	// }
	stateChange() {
		this.setState({
			status: ''
		})
	}
	statusChange() {
		this.setState({
			modalShow: false
		})
	}
	bookName=(e)=>{
		if(e.target.value.length<=20){
            this.setState({ bookName: e.target.value.replace(/[@#%&{}?/><[()（）【】{}《》'“‘”’]+/g,'') })
		}else{
            e.target.value="";
			message.warning('书籍名称不能超过20字！')
		}
	}
	render() {
		return (
			<div className="container">
				<div className="common-title">图书管理
					<div className="filter-search floatR">
						<input type="text" value={this.state.bookName} onChange={this.bookName.bind()} placeholder="书籍名称" />
						<a className="btn search-btn" onClick={() => this.show()}><i className="icon-search"></i></a>
					</div>
				</div>
				<div className="row select-filter clearFix">
					<div className="floatL">
						<select value={this.state.bookState} onChange={(e) => { this.setState({ bookState: e.target.value }, () => { this.show(); }) }}>
							<option value=''>全部状态</option>
							<option value='1'>上架</option>
							<option value='2'>下架</option>
						</select>
					</div>
					<div className="floatL">
						<select value={this.state.operationType} onChange={(e) => { this.setState({ operationType: e.target.value }, () => { this.show(); }) }}>
							<option value=''>全部书籍</option>
							<option value='1'>图书</option>
							<option value='2'>资料</option>
						</select>
					</div>
					<div className="floatL">
						<select value={this.state.bookType} onChange={(e) => { this.setState({ bookType: e.target.value }, () => { this.show(); }) }}>
							<option value=''>全部分类</option>
							{this.state.typeList.map((type, index) => {
								return (
									<option key={index} value={type.code}>{type.name}</option>
								)
							})}
						</select>
					</div>

					<AddBook typeList={this.state.typeList} book={this.state.book} show={this.show.bind(this)}  status={this.state.status} bookId={this.state.bookId} stateChange={this.stateChange.bind(this)} modalShow={this.state.modalShow} texts={this.state.texts} modalShows={this.state.modalShows}/>
				</div>

				<div className="row">
				<Spin spinning={this.state.loading} tip="加载列表中...">
				    <ul className="books-list clearFix" style={{minHeight:'520px'}}>
				    {this.state.BookList.map((book,index)=>{
				    	return(
						       <li key={index}>
							   <img src={pub.getFile(book.bookPath)} alt='book' />
						       	<div className="book-details">
						       	    <p>书籍名称:  {book.bookName}</p>
									{
										book.subhead!==''?	<p>副标题：{book.subhead}</p>
										:''
									}
						       		<p>作者:  {book.author}</p>
						       		{
						       			book.press!==''?<p>出版社: {book.press}</p>
						       			:''
						       		}
						       		
						       		{
						       			book.originalAuthor!==''?<p>原作名: {book.originalAuthor}</p>
						       			:''
						       		}
						       		{
						       			book.translator!==''?<p>译者:  {book.translator}</p>
						       			:''
						       		}
						       		{
						       			book.publishYear!==''?<p>出版年: {book.publishYear}</p>
						       			:''
						       		}
						       		{
						       			Number.isInteger(book.pages)?<p>页数: {book.pages}</p>
						       			:''
						       		}
						       		<p>兑换积分: {book.cashIntegral}</p>
						       		<div className="edit-download">
						       			{book.bookState==='D'?null:<a onClick={()=>this.editBook(book.bookId)} className="green">编辑</a>}
						       			{book.bookState==='D'?
										<p style={{display:"inline-block"}}>
                                        <a style={{backgroundColor:'#ccc',cursor:'default',display:"inlineBlock"}} onClick={()=>this.delBook(book.bookId,1)}>上架</a>
										<a className="red" onClick={()=>this.removeBooks(book.bookId)}>删除</a>
										</p>
										:
										<a className="red" onClick={()=>this.delBook(book.bookId)}>下架</a>
										}
										<a href={pub.getFile(book.bookEntityPath)} download={book.bookEntityPath}>下载</a>
										
						       		</div>
						       	</div>
						       </li>
				    		)
				    })}
				    </ul>
				    </Spin>
				    <div className="line"></div>
					<Pages totalPage={this.state.totalPage} jump={this.jump.bind(this)}/>
				</div>
			</div>

		)
	}

}
export default BookManage

